package com.winit.openapi.util;

import java.io.IOException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.winit.common.spi.SPIException;
import com.winit.openapi.constants.ApiConstant;

public class HttpUtil {

    private final static Logger logger = LoggerFactory.getLogger(HttpUtil.class);

    public static String postJson(String url, String postData) {
        String result = null;
        PostMethod post = null;
        try {
            StringRequestEntity entity = new StringRequestEntity(postData,
                ApiConstant.CONTENT_TYPE_JSON,
                ApiConstant.CHARSET_UTF8);

            post = new PostMethod(url);
            post.setRequestEntity(entity);

            HttpClient client = new HttpClient();
            // 设置连接超时时间
            client.getHttpConnectionManager().getParams().setConnectionTimeout(60 * 1000);
            client.getHttpConnectionManager().getParams().setSoTimeout(60 * 1000);
            int statusCode = client.executeMethod(post);

            if (statusCode == HttpStatus.SC_OK) {
                result = IOUtils.toString(post.getResponseBodyAsStream(), ApiConstant.CHARSET_UTF8);
            } else {
                throw new SPIException("Call API Interface Error: " + post.getStatusText());
            }
        } catch (Exception e) {
            logger.info("调用服务异常：" + e);
        } finally {
            if (post != null) {
                post.releaseConnection();// 会自动释放连接
            }
        }
        return result;
    }

    public static int doGet(String url, String queryString) throws IOException {
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(10 * 1000);
        client.getHttpConnectionManager().getParams().setSoTimeout(10 * 1000);
        client.getParams().setParameter("http.connection.stalecheck", new Boolean(true));
        GetMethod method = new GetMethod(url + "?" + queryString);
        try {
            client.executeMethod(method);
        } finally {
            method.releaseConnection();
        }
        return method.getStatusCode();
    }
}
